<?php

namespace app\api\controller;

use app\api\model\Attention;
use app\api\model\Blacklist;
use app\api\model\ConfigPersonal;
use app\api\model\DymanicCategory;
use app\api\model\DymanicUserlover;
use app\api\model\DymanicUserthumbsup;
use app\api\model\LabelsUser;
use app\api\model\UserActiveval;
use think\Db;
use think\Request;
use app\api\model\Dymanic as DymanicModel;
use app\api\model\ConfigSystem as Config;
use app\api\model\Labels;
use app\api\model\User;
use app\api\model\OrderCommon as Order;
use GatewayClient\Gateway;

class Dymanic extends Common
{
    // 短视频浏览数+1
    public function click()
    {
        /*$dymanic = DymanicModel::where([
            'dy_id' => $this->params['dymanic_id'],
            'type' => 3,
            'shenhe' => 1
        ]);

        if (!$dymanic) return $this->return['dymanic.error.videoNotExist'];

        DymanicModel::where(['dy_id' => $this->params['dymanic_id']])->setInc('visit');

        return $this->return['common.success.default'];*/
    }

    public function category($rec = 1)
    {
         return $this->pass([]);
        $where = ['parent_id'=>0, 'is_hide'=>0];
        if ($rec) {
            $where['is_rec'] = 1;
        }
        $data = Db::name('dymanic_category')->where($where)->order('des desc, id asc')->field('id,name,is_rec')->select();
        return $this->pass($data);
    }

    public function index(Request $request = null)
    {
        return $this->pass([]);

        $config = Config::where(['category' => ['in', ['user', 'shortvideo']]])->cache(86400)->column('title, content');
        
        $nav = $this->params['nav'] ?? 0;               // 1推荐 | 2关注 | 3同城 | 4图集
        $page = $this->params['page'] ?? 1;

        $start = ($page - 1) * 10;

        $join = 'dymanic t1 JOIN user t2 ON t1.userid = t2.id';

        if (isset($this->params['user_id']) && $this->params['user_id']) {
            $response = User::checkLogin($this->params['user_id']);

            $result = $response->getData();

            if ($result['code'] == 400) {
                return $response;
            }

            $this->member = $result['user'];

            $login = 1;
        } else {
            $login = 0;

            if (in_array($nav, [2,3])) {
                return $this->return['user.error.expired'];
            }
        }

        if ($login) {
            $blacklist = Blacklist::lists($this->member['id'], 1);
        } else {
            $blacklist = '';
        }

        for ($i = 0; $i < 1; $i++) {
            if ($nav) {
                $type = $nav == 4 ? 4 : 3;
    
                $type = "t1.type = $type";
            } else {
                if (isset($prev_nav)) {
                    $type = $prev_nav == 4 ? 4 : 3;
    
                    $type = "t1.type = $type";
                } else {
                    $type = "t1.type in (3, 4)";
                }
            }
            
            $where = "$type and t1.shenhe = 1";

            $order = "t1.dy_id desc";

            if ($blacklist) {
                $where .= " and t1.userid not in ($blacklist)";
            }

            if ($login) {
                if (in_array($i, [-1, 0])) {
                    //$video_ids = ShortvideoRecords::where(['user_id' => $this->member['id']])->column('video_id');
                    //cache('video_' . $this->member['id'], null);exit;
                    if ($nav) {
                        $cache_ids = cache('video_' . $this->member['id']);
    
                        if ($cache_ids) {
                            $where .= " and t1.dy_id not in ($cache_ids)";
                        }
                    }
                }

                switch ($nav) {
                    case 1:
                    case 4:
                        $sex = $this->member['sex'] == '男' ? '女' : '男';

                        //$where .= " and t2.sex = '$sex' and (t2.age between " . ($this->member['age'] - 5) . " and " . ($this->member['age'] + 5) . ")";
                        $where .= " and t2.sex = '$sex'";

                        $label_id = LabelsUser::where(['types' => 2, 'user_id' => $this->member['id']])->column('label_id');

                        if ($label_id) {
                            $user_ids = LabelsUser::where([
                                'types' => 1,
                                'user_id' => ['neq', $this->member['id']],
                                'label_id' => ['in', $label_id]]
                            )->column('user_id');

                            if ($user_ids) {
                                $user_ids = implode(',', $user_ids);

                                $where .= " and t1.userid in ($user_ids)";
                            }
                        }

                        break;
                    case 2:
                        $ids = Attention::lists($this->member['id'], 1);
                        $ids = $ids ? "($ids)" : '(0)';

                        $where .= ' and t1.userid in' . $ids;

                        break;
                    case 3:
                        if ($this->member['city']) {
                            $where .= " and t1.citys like '%" . $this->member['city'] . "%'";
                        }

                        break;
                    default:
                        break;
                }
            }

            if ($request->param('userid')) {
                $where .= " and t1.userid = " . $request->param('userid');
            }

            if ($request->param('keywords')) {
                $where .= " and t1.content like '%" . $request->param('keywords') . "%'";
            }

            $whereOr = $where;

            if (in_array($nav, [1, 3, 4])) {
                $order = 'rand()';

                if (in_array($nav, [1])) {
                    $where2 = $where;

                    if ($login && $this->member['city']) {
                        $where .= " and t1.citys like '%" . $this->member['city'] . "%'";
                        $where2 .= " and t1.citys not like '%" . $this->member['city'] . "%'";
                    }
                }
            }

            if ($i <= 0 && $nav) {
                $order = 'rand()';
            }
            
            if (!$nav && isset($prev_nav)) {
                $order = 'rand()';
            }

            $field = "t1.dy_id, t1.type, t1.userid, t1.content, t1.video, t1.cover, t1.citys, t1.lover, t1.thumbsup,
            t1.visit, t1.comments, t1.addtime, t1.price, t1.masterimg images, t2.id, t2.name, t2.age, t2.sex, t2.head_100, t2.nvshen,
            t2.is_identity_authentication, t2.attestation, t2.constellation, t2.noble_grade, t2.noble_time, 
            t2.realname_auth, t2.stature, t2.occupation, t2.register_datetime, t2.hide_distance";

            if ($nav == 1) {
                $sql = "(select $field from $join where $where ORDER BY $order limit 10) 
                    union
                    (select $field from $join where $where2 ORDER BY $order limit 10) 
                    limit $start, 10";
            } else {
                $sql = "select $field from $join where ($where) or ($whereOr) ORDER BY $order limit $start,10";
            }
            // var_dump($sql);exit;
            $data = Db::query($sql);

            if ($data) {
                $start = strtotime(date("Ymd"));

                $gradeNoble = Db::name('grade_noble')->where(['id' => ['gt', 0]])->column('grade, icon');

                if ($login) {
                    if ($nav != 4) {
                        $thumbsups = Db::name('dymanic_userthumbsup')->where(['userid' => $this->member['id']])->column('dy_id');
                        $loves = Db::name('dymanic_userlover')->where(['userid' => $this->member['id']])->column('dy_id');
                        $attentions = Db::name('attention')->where(['user_id' => $this->member['id']])->column('to_user');
                    }
                    
                    $rechargeOrders = Order::where(['types' => 7, 'user_id' => $this->member['id'], 'status' => 1])->column('data');
    
                    $recharges = [];
                    foreach ($rechargeOrders as $item) {
                        $datas = json_decode($item, true);
    
                        $recharges[] = $datas['video_id'];
                    }
                }
    
                if ($nav != 4) {
                    $ids = array_column($data, 'userid');
    
                    $personals = ConfigPersonal::where(['user_id' => ['in', $ids]])->column('user_id, id, hide_distance');
    
                    $user_labels = Labels::lists($ids);
                }

                foreach ($data as $key => $item) {
                    $images_count = count(array_filter(explode(',', $item['images'])));

                    $data[$key]['watch_permission'] = 1;
                    
                    if ($config['recharge_switch']) {
                        $price = $config['unified_price_switch'] ? $config['unified_price'] : $item['price'];
                        
                        if ($price > 0) {
                            if (($login && !in_array($item['dy_id'], $recharges)) || !$login) {
                                if ($item['type'] == 3) {
                                    $item['video'] = '';
                                } else if ($item['type'] == 4) {
                                    $images = array_filter(explode(',', $item['images']));

                                    $item['images'] = $images[0] ?? '';
                                }
                                
                                $data[$key]['watch_permission'] = 0;
                                $data[$key]['price'] = $price;
                            }
                        }
                    }
    
                    if ($nav != 4) {
                        if (isset($personals[$item['userid']]['hide_distance']) && $personals[$item['userid']]['hide_distance']) {
                            $data[$key]['citys'] = '';
                        }
                        $data[$key]['is_new'] = (strtotime($item['register_datetime']) + 86400) > time() ? 1 : 0;
                        $data[$key]['overdue'] = $start > strtotime($item['addtime']) ? 1 : 0;
                        $data[$key]['isthumbsup'] = $login && in_array($item['dy_id'], $thumbsups) ? 1 : 0;
                        $data[$key]['islover'] = $login && in_array($item['dy_id'], $loves) ? 1 : 0;
                        $data[$key]['is_following'] = $login && in_array($item['userid'], $attentions) ? 1 : 0;
                        $data[$key]['num'] = $item['thumbsup'];
    
                        if ($config['hide_city'] && $item['sex'] == '女') {
                            $data[$key]['citys'] = '';
                        }
    
                        $data[$key]['video'] = changeUrl($item['video']);
                        $data[$key]['cover'] = changeUrl($item['cover']);
    
                        $data[$key]['labels'] = $user_labels[$item['userid']] ?? [];
                    }
                    
                    $images = array_filter(explode(',', $item['images']));
                    foreach ($images as $k => $n) {
                        $images[$k] = changeUrl($n);
                    }
                    $data[$key]['images'] = $images;
                    $data[$key]['images_count'] = $images_count;
                    
                    if ($item['noble_grade'] && $item['noble_time'] > time()) {
                        $data[$key]['noble_icon'] = isset($gradeNoble[$item['noble_grade']]) ? changeUrl($gradeNoble[$item['noble_grade']]) : '';

                        $data[$key]['is_vip'] = 1;
                    } else {
                        $data[$key]['noble_icon'] = '';
                        $data[$key]['is_vip'] = 0;
                    }

                    $data[$key]['head_100'] = changeUrl($item['head_100']);
                    
                    unset($data[$key]['noble_grade'], $data[$key]['noble_time'], $data[$key]['register_datetime'],
                        $data[$key]['hide_distance'], $data[$key]['addtime']);
    
                    if ($nav == 4) {
                        unset($data[$key]['video'], $data[$key]['cover'], $data[$key]['lover'], $data[$key]['thumbsup'], $data[$key]['visit'], $data[$key]['comments']);
                    }
                }

                if ($login) {
                    $video_ids = array_column($data, 'dy_id');

                    $cache_ids = cache('video_' . $this->member['id']);
                    $cache_ids = explode(',',$cache_ids);

                    $cache_ids = implode(',', array_merge($cache_ids, $video_ids));

                    if ($nav) {
                        cache('video_' . $this->member['id'], trim($cache_ids, ','));
                    }

                    /*$records = [];
                    foreach ($video_ids as $item) {
                        $records[] = ['user_id' => $this->member['id'], 'video_id' => $item];
                    }

                    (new ShortvideoRecords)->insertAll($records);*/
                }

                $i = 0;
            } else {
                $data = [];

                if (in_array($nav, [1,4]) && $i === 0) {
                    $i = -2;
                    $prev_nav = $nav;
                    $nav = 0;
                } else {
                    cache('video_' . $this->member['id'], NULL);
                    //ShortvideoRecords::destroy(['user_id' => $this->member['id']]);
                }
            }
        }

        return $this->pass($data);
    }
    // 旧版逻辑
    public function listsbak(Request $request = null)
    {
        $blacklist = Blacklist::lists($this->member['id'], true);
        
        $where = "t1.userid = t2.id and t1.shenhe = 1 and t1.type <= 1 and t2.delete_time = 0";
        $order = 't1.dy_id desc';
        
        if ($blacklist) {
            $where .= " and t1.userid not in ($blacklist)";
        }
    
        if ($request->param('type')) {
            $where .= " and t1.type = " . $request->param('type');
    
            $type = 1;
        } else {
            $type = 0;
        }
        
        if ($request->param('userid')) {
            $where .= " and t1.userid = " . $request->param('userid');
        }
        
        if ($request->param('citys')) {
            $where .= " and t1.citys like '%" . $request->param('citys') . "%'";
        }
        
        if ($request->param('sex')) {
            $sex = $request->param('sex') == 1 ? '女' : '男';
            
            $where .= " and t2.sex = '$sex'";
        }
        
        if ($request->param('category_id')) {
            $where .= " and t1.category_id = " . $request->param('category_id');
        }
        
        if ($request->param('following')) {
            $attention = Attention::lists($this->member['id']);
            
            $blacklist = explode(',', $blacklist);
            
            $attention_str = implode(',', array_diff($attention, $blacklist));
            
            $attention_str = $attention_str ?: 0;
            
            $where .= " and t1.userid in ($attention_str)";
        }
    
        $whereOr = $where;
    
        if ($request->param('slide')) {
            $type = 1;
            
            $where .= " and t1.type = 1 and t1.masterimg <> ''";
            $order = "t1.sort desc, t1.visit desc, $order";
        
            $whereOr = $where;
        } else {
            $where_sex = $this->member['sex'] == '男' ? '女' : '男';
            if ($type != 1) {
                $where .= " and t2.sex = '$where_sex' ";
            }
        
            $whereOr .= " and t2.id = " . $this->member['id'];
        }
    
        // 排序
        switch ($request->param('sort')) {
            case 'hot':
                $order = 't1.comments desc, t1.visit desc, ' . $order;
                break;
            case 'new':
                $order = 't1.dy_id desc, ' . $order;
                break;
        }
        
        $page = $request->param('page') ?: 1;
        $startPage = ($page - 1) * 10;
        
        $distance_sql = distance($this->params['latitude'], $this->params['longitude'], 't2');
        
        $field = 't1.*, t2.id, t2.head_100 avatar, t2.nvshen, t2.kejian, t2.name, t2.age, t2.sex,
            t2.is_identity_authentication, t2.attestation, t2.constellation, t2.noble_grade, t2.noble_time, t2.xuni_discount, t2.hide_distance,
            t2.register_datetime, t2.realname_auth';
        
        $sql = "select $field, $distance_sql from dymanic t1, user t2 where ($where) or ($whereOr) order by $order limit $startPage, 10";

        
        $data = Db::query($sql);

        if ($data) {
            $start = strtotime(date("Ymd"));
    
            $loves = DymanicUserlover::where(['userid' => $this->member['id']])->column('dy_id');
            $thumbsups = DymanicUserthumbsup::where(['userid' => $this->member['id']])->column('dy_id');
            $category = DymanicCategory::where(['id' => ['gt', 0]])->column('id, name');
    
            if ($type == 1) {
                $ids = array_column($data, 'to_user');
        
                $users = User::where(['id' => ['in', $ids]])->column('id, name, head_100 avatar');
            }
    
            $ids = array_column($data, 'userid');
            $personals = ConfigPersonal::where(['user_id' => ['in', $ids]])->column('user_id, id, hide_distance');
    
            $config = Config::where(['category' => 'user'])->column('title, content');
            
            foreach ($data as $key => $item) {
                if (isset($personals[$item['userid']]['hide_distance']) && $personals[$item['userid']]['hide_distance']) {
                    $data[$key]['citys'] = '';
                }
                
                $data[$key]['avatar'] = changeUrl($item['avatar']);
                $data[$key]['is_new'] = (strtotime($item['register_datetime']) + 86400) > time() ? 1 : 0;
                $data[$key]['overdue'] = $start > strtotime($item['addtime']) ? 1 : 0;
                $data[$key]['is_vip'] = $item['noble_grade'] && $item['noble_time'] > time() ? 1 : 0;
                $data[$key]['isthumbsup'] = in_array($item['dy_id'], $thumbsups) ? 1 : 0;
                $data[$key]['islover'] = in_array($item['dy_id'], $loves) ? 1 : 0;
    
                $distance = intval($item['xuni_discount']) ? $item['xuni_discount'] : $item['distance'];
                $data[$key]['distance'] = $item['hide_distance'] ? '保密' : ($distance >= 1000 ? number_format(($distance / 1000), 1) . 'km' : number_format($distance, 1) . 'm');
    
                if ($config['hide_city'] && $item['sex'] == '女') {
                    $data[$key]['citys'] = '';
                }
    
                $masterimg = explode(",", $item['masterimg']);
                array_filter($masterimg);
                foreach ($masterimg as $m => $n) {
                    $masterimg[$m] = changeUrl($n);
                }
                $data[$key]['masterimg'] = $masterimg;
    
                $sumbImage = explode(",", $item['sumbImage']);
                array_filter($sumbImage);
                foreach ($sumbImage as $m => $n) {
                    $sumbImage[$m] = changeUrl($n);
                }
                $data[$key]['sumbImage'] = $sumbImage;
    
                if ($type == 1) {
                    $data[$key]['another_name'] = $users[$item['to_user']]['name'] ?? '';
                    $data[$key]['another_avatar'] = $users[$item['to_user']]['avatar'] ? changeUrl($users[$item['to_user']]['avatar']) : '';
        
                    if ($request->param('slide')) {
                        $data[$key]['slide_cover'] = changeUrl($data[$key]['sumbImage'][0]);
                        $data[$key]['slide_cate'] = $category[$item['category_id']] ?? '';
                    }
                } else {
                    $data[$key]['another_name'] = '';
                    $data[$key]['another_avatar'] = '';
                }
            }
        } else {
            $data = [];
        }
        
        return $this->pass($data);
    }
    // 新版去掉聊天查询
    public function lists(Request $request = null)
    {
        if (!$this->member) {
            $this->member = Db::name('user')->where(['reg'=>0])->order('id desc')->find();
        }
        $type = input('type/d', 0);
        $readed = input('readed', 0);
        $zaned = input('zaned', 0);
        $lover = input('lover', 0);
        $class = input('class', 1);
        $category_id = input('category_id', '');
        $topic = input('topic', '');
        $video = input('video', 0);
        $topic_auth = input('topic_auth', '');
        $authed = input('authed', 0);
        $blacklist = Blacklist::lists($this->member['id'], true);


        $page = $request->param('page') ?: 1;
        $pagesize = input('pagesize', 10);
        
        $where = "shenhe = 1 and type <= 1 and private = 0";
        $order = '';
        
        if (!$this->member || $this->member['reg'] == 0) {
            $video = $this->params['video'] = -1;
        }
        

        if ($video) {
            if ($video == -1) {
                $where .= " and dymanic.video = ''";
                if ($page > 1) {
                    return $this->pass([]);
                }
            } else {
                $infos = Db::name('dymanic')->where(['dy_id'=>$video])->find();
                if ($infos) {
                    $where .= " and dy_id <> " . $video . " and dymanic.video <> '' and source_type=0";
                    $cate_childrens = $infos['cate_children'];
                    if ($cate_childrens) {
                        $cate_childrens = explode(',', $cate_childrens);
                        $cate_childrens_where = [];
                        foreach ($cate_childrens as $cate_key => $cate_val) {
                            $cate_childrens_where[] = "find_in_set($cate_val,cate_children)";
                        }
                        if (sizeof($cate_childrens_where)) {
                            $where .= ' and (' . implode(' or ', $cate_childrens_where) . ')';
                            $class = 0;
                        }
                    } else if ($infos['category_id']) {
                        $category_id = $infos['category_id'];
                    }
                }
            }
        }

        $unionWhere = '';
        if ($type) {
            switch ($type) {
                case 1:
                    $unionWhere .= ' and masterimg="" and video=""';
                    break;
                case 3:
                    $unionWhere .= ' and video<>""';
                    break;
                case 4:
                    $unionWhere .= ' and masterimg<>"" and video=""';
                    break;
                
                default:
                    break;
            }
            $where .= $unionWhere;
        }

        if ($authed) {
            $unionWhere .= ' and class=2';
            $where .= ' and class=2';
        }

        $blacklistwhere = $blacklist ? " and id not in ($blacklist)" : "";
    
        $extends = [];
        if ($request->param('keyword')) {
            if ($authed) {
                $where .= " and topic_experience <> '' and (content like '%" . $request->param('keyword') . "%' or topic_experience like '%" . $request->param('keyword') . "%')";
            } else {
                $where .= " and (content like '%" . $request->param('keyword') . "%' or title like '%" . $request->param('keyword') . "%')";
            }
            $extends = $this->extendFunction($request->param('keyword'), 1, 5, false);
        }
        
        if ($request->param('userid')) {
            $where .= " and state = 0 and userid = " . $request->param('userid');
        } else if (!$readed && !$zaned && !$lover && !$request->param('keyword') && !$request->param('following') && !$category_id && !$topic && $class) {
            $where .= " and class=".$class;
        }

        $topic_visit_count = 0;
        if ($topic) {
            if ($authed) {
                $where .= " and (topic_experience like '%&" . $topic . "' or topic_experience like '%&" . $topic . " &%')";
                $topic_visit_count = Db::name('dymanic')->where("shenhe = 1 and (topic_experience like '%&" . $topic . "' or topic_experience like '%&" . $topic . " &%')")->sum('visit');
            } else {
                $where .= " and (topic like '%#" . $topic . "' or topic like '%#" . $topic . "#%')";
                $topic_visit_count = Db::name('dymanic')->where("shenhe = 1 and (topic like '%#" . $topic . "' or topic like '%#" . $topic . "#%')")->sum('visit');
            }
        }

        if ($request->param('citys')) {
            $where .= " and citys like '%" . $request->param('citys') . "%'";
        }
        
        $userwheresex = '';
        // if ($request->param('sex')) {
        //     $userwheresex = $request->param('sex') == 1 ? "sex = '女' and" : "sex = '男' and";
        // }
        
        if ($category_id) {
            $where .= " and category_id = " . $category_id;
        }
        
        if ($request->param('following')) {
            $attention = Attention::lists($this->member['id']);
            
            $blacklist = explode(',', $blacklist);
            
            $attention_str = implode(',', array_diff($attention, $blacklist));
            
            $attention_str = $attention_str ?: 0;
            
            $where .= " and userid in ($attention_str)";
        }
    
        $whereOr = $where;
    
        $mine = false;
        if ($request->param('slide')) {
            $type = 1;
            
            $where .= " and type = 1 and masterimg <> ''";
            $order = "sort desc, visit desc, $order";
        
            $whereOr = $where;
        } else {
            $where_sex = $this->member['sex'] == '男' ? '女' : '男';
            // if ($type != 1 && input('wheresex', 1)) {
            if (!$category_id) {
                $userwheresex = "sex = '" . $where_sex . "' and";
                if (in_array($this->member['entertainment'], [0,2])) {
                    $userwheresex .= " entertainment in (0,2) and age between ".($this->member['age']-10)." and ".($this->member['age']+10)." and";
                }
            }
            
            if (input('userid') && input('user_id') == input('userid')) {
                $mine = true;
            }
        }

        if ($request->param('shang')) {
            $userwheresex = "sex = '男' and";
        }



        $union = "";
        $join = "";
        if (!$request->param('following')) {
            if ($request->param('slide')) {
                $useridsql = "select id from user where reg=1 and is_banned=0 and delete_time = 0 and entertainment>0 $blacklistwhere";
            } else {
                $useridsql = "select id from user where $userwheresex reg=1 and is_banned=0 and delete_time = 0 and entertainment>0 $blacklistwhere";
            }
            // $limitdatetime = '2023-04-15 00:00:00';
            // $limittime = strtotime($limitdatetime);
            // if (strtotime($this->member['register_datetime']) >= $limittime) {
            //     $useridsql .= " and register_datetime >= '" . $limitdatetime . "'";
            // } else {
            //     $useridsql .= " and register_datetime < '" . $limitdatetime . "'";
            // }
            $userids = Db::query($useridsql);
            if($userids){
                $userids = array_column($userids, 'id');
                $attention_str = implode(',', $userids);
                $where .= " and dymanic.userid in ($attention_str)";
            }
            if($mine && $request->param('userid')){
                $union = "union select * from dymanic where type=".$type." and state = 0 and shenhe < 2 and userid=" . $request->param('userid') . $unionWhere;
            } else {
                $join = 'left join user on dymanic.userid=user.id';
                if ($this->member['age'] && $category_id === '0' && !$video) {
                    $where .= " and user.age between " . ($this->member['age'] - 20) . " and " . ($this->member['sex'] == '女' ? $this->member['age'] + 20 : $this->member['age'] + 3);
                }

                $sexSet = $this->member['sex'] == '男' ? '女' : '男';
                if (strtotime($this->member['register_datetime']) < strtotime('2023-08-01')){
                    $where .= ' and (user.register_datetime >= "2023-08-01" or user.id='.$this->member['id'].' or (user.register_datetime < "2023-08-01" && user.sex="'.$sexSet.'"))';
                }
                $entertainment = input('entertainment');
                if ($entertainment || $entertainment === '0') {
                    $where .= ' and user.entertainment='.$entertainment .' and user.sex="'.$sexSet.'"';
                }

                if ($readed) {
                    $join .= ' inner join dymanic_read on dymanic.dy_id=dymanic_read.dy_id';
                    $where .= ' and dymanic_read.userid='.$this->member['id'];
                }

                if ($zaned) {
                    $join .= ' inner join dymanic_userthumbsup on dymanic.dy_id=dymanic_userthumbsup.dy_id';
                    $where .= ' and dymanic_userthumbsup.userid='.$this->member['id'];
                }

                if ($lover) {
                    $join .= ' inner join dymanic_userlover on dymanic.dy_id=dymanic_userlover.dy_id';
                    $where .= ' and dymanic_userlover.userid='.$this->member['id'];
                }

            }
        }

        $startPage = ($page - 1) * $pagesize;

        // 排序
        switch ($request->param('sort')) {
            case 'hot':
                $order = 'liveness desc' . ($order ? ','. $order : '');
                break;
            case 'new':
                $order = 'dy_id desc' . ($order ? ','. $order : '');
                break;
            default:
                $order = 'top desc, dy_id desc';
                break;
        }

        // if (!isset($entertainment) && !$request->param('category_id') && !$request->param('following') && !$request->param('userid') && !$request->param('keyword')) {
        if ($category_id === '0' && !$video) {
            $order = 'liveness desc, dy_id desc';
            if ($page == 1) {
                cache('dylists:offset:'.$this->member['id'], rand(0,30), 600);
            }
            $offset = cache('dylists:offset:'.$this->member['id']) ?? 0;
            $startPage += $offset;
        }

        if ($readed) {
            $order = 'dymanic_read.id desc';
        }
        if ($zaned) {
            $order = 'dymanic_userthumbsup.id desc';
        }
        if ($lover) {
            $order = 'dymanic_userlover.time desc';
        }
        
        
        // var_dump($order);exit;

        
        $fielduser = 'id, head_100 avatar, nvshen, kejian, name, age, sex,
            is_identity_authentication, attestation, constellation, noble_grade, noble_time, xuni_discount, hide_distance,
            register_datetime, realname_auth, longitude, latitude, real_avatar, auth_tag';
        $field = 'dymanic.*';
        $sql = "select $field from dymanic $join where $where $union order by $order limit $startPage, $pagesize";
        $CountSql = "select count(dymanic.dy_id) count from dymanic $join where $where $union";
        if ($union) {
            $CountSql = str_replace('*', 'count(dymanic.dy_id) count', $CountSql);
        }

        $cacheKey = md5($sql);
        $cacheKey2 = md5($CountSql);
        $data = cache($cacheKey);
        $count = cache($cacheKey2);
        if (!$data) {
            $data = Db::query($sql);
            $count = Db::query($CountSql);
            cache($cacheKey, $data, 60);
            cache($cacheKey2, $count, 60);
        }
        // var_dump($sql);exit;
        $count = $count[0]['count'];

        // var_dump($data);exit;

        if ($data) {
            $start = strtotime(date("Ymd"));
    
            $loves = DymanicUserlover::where(['userid' => $this->member['id']])->column('dy_id');
            $thumbsups = DymanicUserthumbsup::where(['userid' => $this->member['id']])->column('dy_id');
            $attentions = Db::name('attention')->where(['user_id' => $this->member['id']])->column('to_user');
            $category = DymanicCategory::where(['id' => ['gt', 0]])->column('id, name');
    
            if ($type == 1) {
                $ids = array_column($data, 'to_user');
        
                $users = User::where(['id' => ['in', $ids]])->column('id, name, head_100 avatar');
            }
    
            $ids = array_column($data, 'userid');
            $personals = ConfigPersonal::where(['user_id' => ['in', $ids]])->column('user_id, id, hide_distance');
    
            $config = Config::where(['category' => 'user'])->column('title, content');
            $dyusers = Db::name('user')->where(['id'=>['in', array_column($data, 'userid')]])->column($fielduser, 'id');
            $returnData = [];



            $extend_func_ids = array_filter(array_unique(array_column($data, 'extend_func_id')));
            if (sizeof($extend_func_ids)) {
                $extend_funcs = Db::name('extend_function')->where(['id'=>['in', $extend_func_ids]])->column('id,name,icon,path', 'id');
            } else {
                $extend_funcs = [];
            }
            
            foreach ($data as $key => $item) {
                if(!isset($dyusers[$item['userid']])){
                    continue;
                }
                $dyuser = $dyusers[$item['userid']];
                $item = array_merge($item, $dyuser);
                $data[$key]['id'] = $item['id'];

                if($item['extend_func_id']) {
                    $data[$key]['extend_func_info'] = $extend_funcs[$item['extend_func_id']] ?? false;
                }

                // if (isset($personals[$item['userid']]['hide_distance']) && $personals[$item['userid']]['hide_distance']) {
                //     $data[$key]['citys'] = '';
                // }
                
                $data[$key]['name'] = $item['name'] ?? '';
                $data[$key]['avatar'] = isset($item['avatar']) && $item['avatar'] ? changeUrl($item['avatar']) . '?x-oss-process=image/resize,w_100/quality,q_50' : '';
                try {
                    $data[$key]['is_vip'] = $item['noble_grade'] && $item['noble_time'] > time() ? 1 : 0;
                    $data[$key]['is_new'] = $item['register_datetime'] && (strtotime($item['register_datetime']) + 86400) > time() ? 1 : 0;
                } catch (\Exception $e) {
                    $data[$key]['is_new'] = 0;
                    $data[$key]['is_vip'] = 0;
                }
                $data[$key]['auth_tag'] = $item['auth_tag'];
                $data[$key]['overdue'] = $start > strtotime($item['addtime']) ? 1 : 0;
                $data[$key]['is_attention'] = in_array($item['userid'], $attentions) ? 1 : 0;
                $data[$key]['isthumbsup'] = in_array($item['dy_id'], $thumbsups) ? 1 : 0;
                $data[$key]['islover'] = in_array($item['dy_id'], $loves) ? 1 : 0;
                $data[$key]['real_avatar'] = $item['real_avatar'] ?? '';
    
                if(intval($item['xuni_discount'] ?? 0)){
                    $distance = $item['xuni_discount'];
                }else{
                    $distance = _distance($item['longitude'], $item['latitude'], $this->params['longitude'], $this->params['latitude']);
                }
                $data[$key]['distance'] = $item['hide_distance'] ? '保密' : ($distance >= 1000 ? number_format(($distance / 1000), 1) . 'km' : number_format($distance, 1) . 'm');
    
                // if ($config['hide_city'] && $item['sex'] == '女') {
                //     $data[$key]['citys'] = '';
                // }
    
                $masterimg = explode(",", $item['masterimg']);
                $masterimg = array_unique(array_filter($masterimg));
                foreach ($masterimg as $m => $n) {
                    $masterimg[$m] = changeUrl($n) . '?x-oss-process=image/resize,w_400/quality,q_80';
                }
                $data[$key]['masterimg'] = $masterimg;

                $sumbImage = explode(",", $item['sumbImage']);
                $sumbImage = array_unique(array_filter($sumbImage));
                foreach ($sumbImage as $m => $n) {
                    $sumbImage[$m] = changeUrl($n) . '?x-oss-process=image/resize,w_400/quality,q_80';
                }
                $data[$key]['sumbImage'] = $sumbImage;
    
                // if ($type == 1) {
                //     $data[$key]['another_name'] = $users[$item['to_user']]['name'] ?? '';
                //     $data[$key]['another_avatar'] = $users[$item['to_user']]['avatar'] ? changeUrl($users[$item['to_user']]['avatar']) : '';
        
                //     if ($request->param('slide')) {
                //         $data[$key]['slide_cover'] = changeUrl($data[$key]['sumbImage'][0]);
                //         $data[$key]['slide_cate'] = $category[$item['category_id']] ?? '';
                //     }
                // } else {
                //     $data[$key]['another_name'] = '';
                //     $data[$key]['another_avatar'] = '';
                // }
                switch ((int)$item['source_type']) {
                    case 1:
                        $data[$key]['source_info'] = action('api/flag/flagsInfo', ['flags_id'=>$item['source_id'], 'returnJson'=>false]);
                        break;
                    case 3:
                        $data[$key]['source_info'] = Db::name('user_service')->where(['id'=>$item['source_id']])->field('title,price,image,method')->find();
                        break;
                    case 4:
                        $source_info = Db::name('activity_offline')->where(['id'=>$item['source_id']])->field('address_name,sex,pay,price,content,images')->find();
                        if ($source_info && $source_info['images']) {
                            $source_info['images'] = explode(',', $source_info['images']);
                        }
                        $data[$key]['source_info'] = $source_info;
                        break;
                }
                $data[$key]['commentList'] = Db::name('dycomment')->where(['dy_id'=>$item['dy_id'], 'shenhe'=>1])->limit(3)->order('comment_id desc')->field('userid,content')->select();
                if (sizeof($data[$key]['commentList'])) {
                    foreach ($data[$key]['commentList'] as &$val) {
                        $val['user'] = _user_cache($val['userid']);
                    }
                }
                $data[$key]['thumbsup'] += $item['xuni_thumbsup'];
                unset($data[$key]['xuni_thumbsup']);


                if ($data[$key]['topic']) {
                    $topic = explode('#',$data[$key]['topic']);
                    $data[$key]['topic'] = [];
                    foreach ($topic as &$v) {
                        if ($v) $data[$key]['topic'][] = $v;
                    }
                } else {
                    $data[$key]['topic'] = [];
                }

                if ($data[$key]['topic_experience']) {
                    $topic_experience = array_filter(explode('&',$data[$key]['topic_experience']));
                    $data[$key]['topic_experience'] = [];
                    foreach ($topic_experience as &$v) {
                        $data[$key]['topic_experience'][] = $v;
                    }
                } else {
                    $data[$key]['topic_experience'] = [];
                }


                $data[$key]['price'] *= getenv('APP_RATE');
                if ($data[$key]['class'] == 2 && $data[$key]['userid'] != $this->member['id']) {
                    $data[$key]['paystate'] = Db::name('order_of_subscribe')->where(['user_id'=>$this->member['id'], 'dy_id'=>$data[$key]['dy_id']])->count();
                } else {
                    $data[$key]['paystate'] = 1;
                }

                $returnData[] = $data[$key];
            }
        } else {
            $returnData = [];
        }


        if ($request->param('keyword')) {
            $has = Db::name('search_history')->where(['content' => $request->param('keyword')])->find();
            if ($has) {
                Db::name('search_history')->where(['id' => $has['id']])->update(['time' => time(), 'result' => sizeof($returnData)]);
            } else {
                Db::name('search_history')->insert(['user_id' => $this->member['id'], 'content' => $request->param('keyword'), 'time' => time(), 'result' => sizeof($returnData)]);
            }
        }
        
        return $this->pass($returnData, 'data', compact('extends', 'topic_visit_count', 'count'));
    }


    public function hotword() {
        $where = ['result' => ['>', 1]];

        $lastRecord = session('last_record');
        if ($lastRecord) {
            $where['content'] = ['not in', $lastRecord];
        }

        $data = Db::name('search_history')
            ->where($where)
            ->where('content <> ""')
            ->order(Db::raw('rand()'))
            ->limit(10)
            ->column('content');
        session('last_record', $data);

        return $this->pass($data);
    }


    public function hotlist() {
        $type = Db::name('dynamic_rank_type')->order('sort desc, id asc')->field('id,title,class,category')->select();

        foreach ($type as &$value) {
            $list = Db::name('dynamic_rank')
                ->where(['type_id' => $value['id']])
                ->field('dy_id,title')
                ->order('sort desc, id asc')
                ->limit(10)
                ->select();
            if (empty($list) && ($value['class'] || $value['category'])) {
                $where = ['shenhe' => 1];
                if ($value['category']) {
                    $where['category_id'] = $value['category'];
                } else {
                    $where['class'] = $value['class'];
                }
                $list = Db::name('dymanic')
                    ->where($where)
                    ->field('dy_id,content title')
                    ->order('liveness desc')
                    ->limit(10)
                    ->select();
            }
            $value['list'] = $list;
            unset($value['class'], $value['category']);
        }

        return $this->pass($type);
    }


    public function share($dy_id)
    {
        $userid = $this->member['id'];

        if ($userid && !cache('dyshare:'. $userid . ':dyid' . $dy_id)) {
            $data = Db::name('dymanic')->where(['shenhe'=>1])->find($dy_id);
            if (!$data) return;
            Db::name('dymanic')
                ->where(['dy_id' => $dy_id])
                ->update([
                    'shares'  =>  Db::raw('shares+1'),
                    // 'liveness'  =>  _calculateHotScore($data['visit'], $data['comments'], $data['thumbsup'], ++$data['shares'])
                ]);
            Db::name('dymanic_share')->insert(['user_id'=>$userid, 'dy_id'=>$dy_id, 'time'=>time()]);
            cache('dyshare:'. $userid . ':dyid' . $dy_id, $dy_id, 60);
        }
        return $this->pass('success');
    }



    public function extendFunction($keyword = '', $page = 1, $pagesize = 20, $returnJson = true)
    {
        $extendWhere = [
            'is_hidden' => 0,
            'name'  => ['like', $keyword . '%'],
        ];
        $extend = Db::name('extend_function')
            ->where($extendWhere)
            ->page($page)
            ->limit($pagesize)
            ->field('id,name,icon,description,path')
            ->order('sort desc, id asc')
            ->select();
        return $returnJson ? $this->pass($extend) : $extend;
    }


    public function rmvisit($dy_id)
    {
        $res = Db::name('dymanic_read')->where(['dy_id'=>$dy_id, 'userid'=>$this->member['id']])->delete();
        return $res ? $this->pass('删除成功') : $this->miss('删除失败');
    }

    public function rmallvisit()
    {
        $res = Db::name('dymanic_read')->where(['userid'=>$this->member['id']])->delete();
        return $res ? $this->pass('移除成功') : $this->miss('移除失败');
    }

    public function rmalllover()
    {
        $dys = Db::name('dymanic_userlover')->where(['userid'=>$this->member['id']])->column('dy_id');
        if (empty($dys)) return $this->miss('暂无收藏');

        // $dys = Db::name('dymanic')->where(['dy_id'=>['in', $dyids], 'source_type'=>5])->column('source_id');
        // if (sizeof($dys)) {
        //     Db::connect('database9')->name('dymanic')->where(['dy_id'=>['in', $dys]])->setDec('lover');
        //     Db::connect('database9')->name('dymanic_userlover')->where(['userid'=>$this->member['id'], 'dy_id'=>['in', $dys]])->delete();
        // }

        // $dyids2 = Db::connect('database9')->name('dymanic_userlover')->where(['userid'=>$this->member['id']])->column('dy_id');
        // if (sizeof($dyids2)) {
        //     Db::connect('database9')->name('dymanic')->where(['dy_id'=>['in', $dyids2]])->setDec('lover');
        //     Db::connect('database9')->name('dymanic_userlover')->where(['userid'=>$this->member['id'], 'dy_id'=>['in', $dyids2]])->delete();
        // }

        // $dys = Db::name('dymanic')->where(['dy_id'=>['in', $dyids], 'source_type'=>['<>', 5]])->column('dy_id');
        if (sizeof($dys)) {
            Db::name('dymanic')->where(['dy_id'=>['in', $dys]])->setDec('lover');
        }
        Db::name('dymanic_userlover')->where(['userid'=>$this->member['id']])->delete();
        return $this->pass('移除成功');
    }

    public function rmallzan()
    {
        $dys = Db::name('dymanic_userthumbsup')->where(['userid'=>$this->member['id']])->column('dy_id');

        // $dys = Db::name('dymanic')->where(['dy_id'=>['in', $dyids], 'source_type'=>5])->column('source_id');
        // if (sizeof($dys)) {
        //     Db::connect('database9')->name('dymanic')->where(['dy_id'=>['in', $dys]])->setDec('thumbsup');
        //     Db::connect('database9')->name('dymanic_userthumbsup')->where(['userid'=>$this->member['id'], 'dy_id'=>['in', $dys]])->delete();
        // }

        // $dyids2 = Db::connect('database9')->name('dymanic_userthumbsup')->where(['userid'=>$this->member['id']])->column('dy_id');
        // if (sizeof($dyids2)) {
        //     Db::connect('database9')->name('dymanic')->where(['dy_id'=>['in', $dyids2]])->setDec('thumbsup');
        //     Db::connect('database9')->name('dymanic_userthumbsup')->where(['userid'=>$this->member['id'], 'dy_id'=>['in', $dyids2]])->delete();
        // }

        // $dys = Db::name('dymanic')->where(['dy_id'=>['in', $dyids], 'source_type'=>['<>', 5]])->column('dy_id');
        if (sizeof($dys)) {
            Db::name('dymanic')->where(['dy_id'=>['in', $dys]])->setDec('thumbsup');
        }
        Db::name('dymanic_userthumbsup')->where(['userid'=>$this->member['id']])->delete();

        return $this->pass('移除成功');
    }


    public function thumbsup($dy_id = 0, $type = 1)
    {
        $user_id = $this->member['id'];
        $result = false;
        if (!$dy_id) {
            return $this->miss("操作失败");
        }
        $dymanic = Db::name('dymanic')->where(['dy_id'=>$dy_id])->find();
        if (!$dymanic) {
            return $this->miss("操作失败");
        }

        if ($dymanic['source_type'] == 6) {
            if ($this->member['reg'] != 3) {
                $this->member = Db::name('user')->where(['reg'=>2, 'authcode'=>$this->member['id']])->find();
                IF (!$this->member) {
                    return $this->miss("未创建匿名电台账号");
                }
                $user_id = $this->member['id'];
            }
        }
        $thumbsup = Db::name('dymanic_userthumbsup')->where(['dy_id' => $dy_id, 'userid' => $user_id])->count();
        switch ((int)$type) {
            case 1:
                if ($thumbsup) {
                    return $this->pass("点赞成功");
                }
                $code = Db::name('dymanic')
                            ->where(['dy_id'=>$dy_id])
                            ->update([
                                'thumbsup'  =>  Db::raw('thumbsup+1'),
                                // 'liveness'  =>  _calculateHotScore($dymanic['visit'], $dymanic['comments'], ++$dymanic['thumbsup'], $dymanic['shares'])
                            ]);
                Db::name('dymanic_userthumbsup')->insert(['userid'=>$user_id, 'dy_id'=>$dy_id]);
                if ($code) {
                    UserActiveval::inc($user_id, 'dynamic_thumb');
                    $result = true;
                }
                Db::name('user')->where(['id' => $dymanic['userid']])->setInc('charm_value', 1);

                if ($dymanic['source_type'] == 5) {
                    Db::connect('database9')->name('dymanic_userthumbsup')->insert(['userid'=>$user_id, 'dy_id'=>$dymanic['source_id']]);
                    Db::connect('database9')->name('dymanic')->where(['dy_id'=>$dymanic['source_id']])->setInc('thumbsup');
                }

                $touserid = $dymanic['userid'];
                if ($touserid && $touserid != $user_id && $dymanic['state'] == 0) {
                    $message = [
                        'type' => 12,
                        'to_user' => $touserid,
                        'context' => json_encode([
                                        'name' => $this->member['name'],
                                        'head' => $this->member['head_100'],
                                        'dy_id' => $dy_id
                                    ], JSON_UNESCAPED_UNICODE),
                        'uid' => $this->member['id'],
                        'user_id'=>$dy_id
                    ];

                    Db::name('sys_message')->insert($message);


                    $Gatewaymessage = json_encode([
                        "code" => 200,
                        "action" => 'api/Privatechat/interactionCount',
                        'data' => []
                    ]);

                    Gateway::sendToUid(getenv('SOCKET_PREFIX') . $touserid, $Gatewaymessage);
                }


                break;
            case 2:
                if (!$thumbsup) {
                    return $this->pass('已取消');
                }
                $code = Db::name('dymanic')
                            ->where(['dy_id'=>$dy_id])
                            ->update([
                                'thumbsup'  =>  Db::raw('thumbsup-1'),
                                // 'liveness'  =>  _calculateHotScore($dymanic['visit'], $dymanic['comments'], ++$dymanic['thumbsup'], $dymanic['shares'])
                            ]);
                Db::name('dymanic_userthumbsup')->where(['userid'=>$user_id, 'dy_id'=>$dy_id])->delete();
                if ($code) {
                    $result = true;
                }
                Db::name('user')->where(['id' => $dymanic['userid']])->setDec('charm_value', 1);

                if ($dymanic['source_type'] == 5) {
                    Db::connect('database9')->name('dymanic_userthumbsup')->where(['userid'=>$user_id, 'dy_id'=>$dymanic['source_id']])->delete();
                    Db::connect('database9')->name('dymanic')->where(['dy_id'=>$dymanic['source_id']])->setDec('thumbsup');
                }
                break;
            default:
                break;
        }
        return $result ? $this->pass($type==1?'点赞成功':'已取消点赞') : $this->miss($type?'点赞失败':'取消点赞失败');
    }

    public function lover($type = 1, $dy_id)
    {
        $userid = $this->member['id'];
        $dymanic = Db::name('dymanic')->find($dy_id);
        switch ($type) {
            case 1:
                $has = Db::name('dymanic_userlover')->where(['userid'=>$userid, 'dy_id'=>$dy_id])->count();
                if ($has) {
                    return $this->pass('已收藏');
                }
                $res = Db::name('dymanic_userlover')->insert(['userid'=>$userid, 'dy_id'=>$dy_id, 'time'=>time()]);
                if ($res) {
                    Db::name('dymanic')->where(['dy_id'=>$dy_id])->setInc('lover');
                    Db::name('user')->where(['id' => $dymanic['userid']])->setInc('charm_value', 5);
                    // if ($dymanic['source_type'] == 5) {
                    //     Db::connect('database9')->name('dymanic_userlover')->insert(['userid'=>$userid, 'dy_id'=>$dymanic['source_id'], 'time'=>time()]);
                    //     Db::connect('database9')->name('dymanic')->where(['dy_id'=>$dymanic['source_id']])->setInc('lover');
                    // }
                    
                    $touserid = $dymanic['userid'];
                    if ($touserid && $touserid != $userid && $dymanic['state'] == 0) {
                        $message = [
                            'type' => 18,
                            'to_user' => $touserid,
                            'context' => json_encode([
                                            'name' => $this->member['name'],
                                            'head' => $this->member['head_100'],
                                            'dy_id' => $dy_id
                                        ], JSON_UNESCAPED_UNICODE),
                            'uid' => $this->member['id'],
                            'user_id'=>$dy_id
                        ];

                        Db::name('sys_message')->insert($message);


                        $Gatewaymessage = json_encode([
                            "code" => 200,
                            "action" => 'api/Privatechat/interactionCount',
                            'data' => []
                        ]);

                        Gateway::sendToUid(getenv('SOCKET_PREFIX') . $touserid, $Gatewaymessage);
                    }
                    return $this->pass('收藏成功');
                }
                return $this->miss('收藏失败');
                break;
            case 2:
                $res = Db::name('dymanic_userlover')->where(['userid'=>$userid, 'dy_id'=>$dy_id])->delete();
                if ($res) {
                    Db::name('dymanic')->where(['dy_id'=>$dy_id])->setDec('lover');
                    Db::name('user')->where(['id' => $dymanic['userid']])->setDec('charm_value', 5);
                    // if ($dymanic['source_type'] == 5) {
                    //     Db::connect('database9')->name('dymanic_userlover')->where(['userid'=>$userid, 'dy_id'=>$dymanic['source_id']])->delete();
                    //     Db::connect('database9')->name('dymanic')->where(['dy_id'=>$dymanic['source_id']])->setDec('lover');
                    // }
                    return $this->pass('取消收藏成功');
                }
                return $this->miss('取消收藏失败');
            default:
                return $this->miss('操作错误');
                break;
        }
    }

    public function listCount()
    {
        $userid = $this->member['id'];
        $userid_privacy = Db::name('user')->where(['reg'=>2, 'authcode'=>$userid])->value('id');
        if ($userid_privacy) {
            $count[] = Db::name('dymanic')->where(['userid'=>['in',[$userid_privacy,$userid]], 'shenhe'=>['<', 2], 'state'=>0,'addway'=>['>',1]])->count();
        } else {
            $count[] = Db::name('dymanic')->where(['userid'=>$userid, 'shenhe'=>['<', 2], 'state'=>0,'addway'=>['>',1]])->count();
        }
        $count[] = Db::name('dymanic_userlover')->alias('a')->join('dymanic b', 'a.dy_id=b.dy_id')->where(['a.userid'=>$userid, 'b.shenhe'=>['<', 2]])->count();
        $count[] = Db::name('dymanic_read')->alias('a')->join('dymanic b', 'a.dy_id=b.dy_id')->where(['a.userid'=>$userid, 'b.shenhe'=>['<', 2]])->group('a.dy_id')->count();
        $count[] = Db::name('dymanic_userthumbsup')->alias('a')->join('dymanic b', 'a.dy_id=b.dy_id')->where(['a.userid'=>$userid, 'b.shenhe'=>['<', 2]])->count();

        return $this->pass($count);
    }



    public function Notice($type = 1, $page = 1, $pagesize = 20)
    {
        $map = ['to_user'=>$this->member['id']];
        switch ((int)$type) {
            case 1:
                $map['type'] = ['in', [12,18]];
                break;
            case 2:
                $map['type'] = 1;
                break;
            case 3:
                $map['type'] = 17;
                break;
            
            default:
                return $this->miss('类别错误');
                break;
        }
        $data = Db::name('sys_message')
                    ->where($map)
                    ->page($page)
                    ->limit($pagesize)
                    ->order('is_read asc, id desc')
                    ->field('channel,dymanic_city,sound_tip,is_top', 'filter')
                    ->select();

        $read = [];
        foreach ($data as &$value) {
            if ($value['is_read'] == 0) {
                $read[] = $value['id'];
            }
            $value['context'] = json_decode($value['context'], true);
        }

        if (in_array($type, [1,3])) {
            $dymanics = Db::name('dymanic')->where(['dy_id'=>['in',array_column($data, 'user_id')]])->column('source_type,source_id,video', 'dy_id');

            foreach ($data as &$value) {
                $value['source_type'] = $dymanics[$value['user_id']]['source_type'] ?? '';
                $value['source_id'] = $dymanics[$value['user_id']]['source_id'] ?? '';
                $value['video'] = $dymanics[$value['user_id']]['video'] ?? '';
            }
        }

        if (sizeof($read)) {
            Db::name('sys_message')->where(['id'=>['in', $read]])->update(['is_read'=>1]);
        }
        $Gatewaymessage = json_encode([
            "code" => 200,
            "action" => 'api/Privatechat/interactionCount',
            'data' => []
        ]);
        Gateway::sendToUid(getenv('SOCKET_PREFIX') . $this->member['id'], $Gatewaymessage);
        return $this->pass($data);
    }


    public function interactionCount()
    {
        $userid = $this->member['id'];
        $map = ['to_user'=>$userid, 'is_read' => 0];
        $map['type'] = ['in', [12,18]];
        $data['zan_and_lover'] = Db::name('sys_message')
                    ->where($map)
                    ->count();
        $map['type'] = 1;
        $data['attention'] = Db::name('sys_message')
                    ->where($map)
                    ->count();
        $map['type'] = 17;
        $data['comment'] = Db::name('sys_message')
                    ->where($map)
                    ->count();
        $data['count'] = $data['zan_and_lover'] + $data['attention'] + $data['comment'];
        Gateway::sendToUid(getenv('SOCKET_PREFIX') . $userid, json_encode(['action' => 'api/Dymanic/interactionCount', 'data' => $data]));
    }



    public function comments($dy_id = 0, $page = 1, $pagesize = 10, $returnJson = true) {
        $data = Db::name('dycomment')
            ->field("comment_id,content,touserid,addtime,userid")
            ->where(['dy_id' => $dy_id, 'shenhe' => 1])
            ->where("(userid=" . ($this->member['id'] ?? 0). " and `from`=0) or userid<>".($this->member['id']??0))
            ->limit(($page - 1) * $pagesize, $pagesize)
            ->order('addtime desc')
            ->select();

        $uids = explode(',', implode(',', array_filter(array_unique(array_column($data, 'touserid')))));
        $uids = array_filter(array_unique(array_merge(array_column($data, 'userid'), $uids)));
        $users     = [];
        if ($uids) {
            $users = [];
            $userstmp = Db::name('user')->where(['id' => ['in', $uids]])->column('id,name,head_portrait');
            foreach ($userstmp as &$value) {
                $value['head_portrait'] = _ossUrl() . $value['head_portrait'];
                $users[$value['id']] = $value;
            }
        }
        $article = Db::name('dymanic')->where(['dy_id'=>$dy_id])->field('dy_id,userid,class')->find();

        foreach ($data as &$value) {
            $value['addtime'] = _time(strtotime($value['addtime']));
            // 如果存在@对象

            if (isset($users[$value['userid']])) {
                $value = array_merge($value, $users[$value['userid']]);
            }
        }
        return $returnJson ? $this->pass($data) : $data;
    }

    public function setPrivate($dy_id = '', $state = 0)
    {
        if (!in_array($state, [0,1])) return $this->miss('操作异常');

        $dy = Db::name('dymanic')->where(['dy_id'=>$dy_id,'userid'=>$this->member['id']])->find();
        if (!$dy) return $this->miss('动态不存在');
        if ($dy['private'] == $state) return $this->pass('设置成功');
        if ($state == 1) {
            $in_mix = Db::name('dymanic_collection_term')->where(['dy_id'=>$dy_id])->find();
            if ($in_mix) return $this->miss('合集作品不可设为私密');
        }
        $res = Db::name('dymanic')->where(['dy_id'=>$dy_id])->update(['private'=>$state]);
        return $res ? $this->pass('设置成功') : $this->miss('操作失败');
    }

    public function setTop($dy_id = '', $state = 0)
    {
        if (!in_array($state, [0,1])) return $this->miss('操作异常');

        $dy = Db::name('dymanic')->where(['dy_id'=>$dy_id,'userid'=>$this->member['id']])->find();
        if (!$dy) return $this->miss('动态不存在');
        if ($dy['top'] == $state) return $this->pass('设置成功');
        if ($state) {
            Db::name('dymanic')->where(['top'=>1])->update(['top'=>0]);
        }
        $res = Db::name('dymanic')->where(['dy_id'=>$dy_id])->update(['top'=>$state]);
        return $res ? $this->pass('设置成功') : $this->miss('操作失败');
    }

    public function uninterested($dy_id = '')
    {
        $dy = Db::name('dymanic')->where(['dy_id'=>$dy_id,'shenhe'=>1,'private'=>0])->find();
        if (!$dy) return $this->miss('操作异常');
        $obj = [];
        $user = _user_cache($dy['userid']);
        $obj[] = [
            'title'=>'用户',
            't'=>'user',
            'c'=> ['id'=>$user['id'], 'name'=>$user['name']]
        ];
        $topics = [];
        if ($dy['topic']) {
            $topic = explode('#',$dy['topic']);
            foreach ($topic as &$v) {
                if ($v) $topics[] = $v;
            }
        }
        if ($dy['topic_experience']) {
            $topic_experience = array_filter(explode('&',$dy['topic_experience']));
            foreach ($topic_experience as &$v) {
                $topics[] = $v;
            }
        }
        if (sizeof($topics)) {
            foreach ($topics as $key => $value) {
                $obj[] = [
                    'title'=>'话题',
                    't'=>'topic',
                    'c'=>$value
                ];
            }
        }

        $has = Db::name('dymanic_uninterested')->where(['dy_id'=>$dy_id, 'user_id'=>$this->member['id']])->find();
        if ($has) return $this->pass(['id'=>$has['id'], 'obj'=>$obj]);

        $res = Db::name('dymanic_uninterested')->insertGetId(['dy_id'=>$dy_id, 'user_id'=>$this->member['id'], 'time'=>time()]);
        return $res ? $this->pass(['id'=>$res, 'obj'=>$obj]) : $this->miss('fail');
    }

    public function uninterested_desc($id = '', $donotlike = [], $content = '')
    {
        $has = Db::name('dymanic_uninterested')->where(['id'=>$id, 'user_id'=>$this->member['id'], 'donotlike_object'=>'', 'content_reason'=>''])->find();
        if (!$has) return $this->pass('');

        if (sizeof($donotlike)) {
            foreach ($donotlike as &$value) {
                unset($value['title']);
                if ($value['t'] == 'user') {
                    $value['c'] = $value['c']['id'];
                }
            }
            $donotlike = json_encode($donotlike, JSON_UNESCAPED_UNICODE);
        }

        $res = Db::name('dymanic_uninterested')->where(['id'=>$id])->update(['donotlike_object'=>$donotlike, 'content_reason'=>$content]);
        if ($res) {
            if ($content) {
                $res = Db::name('dymanic_report')->insertGetId(['dy_id'=>$has['dy_id'], 'user_id'=>$this->member['id'], 'desc'=>$content, 'create_time'=>time()]);
            }
        }
        return $res ? $this->pass('感谢您的反馈') : $this->miss('fail');
    }
    public function reportTemplate()
    {
        $data = ['相似过多', '广告营销', '恶心恐怖', '色情低俗', '虚假夸张'];
        return $this->pass($data);
    }
    public function report($dy_id = '', $desc = '', $content = '')
    {
        $dy = Db::name('dymanic')->where(['dy_id'=>$dy_id,'shenhe'=>1,'private'=>0])->find();
        if (!$dy) return $this->miss('操作异常');
        if (!$desc && !$content) return $this->miss('请选择或填写原因');
        $res = Db::name('dymanic_report')->insertGetId(['dy_id'=>$dy_id, 'user_id'=>$this->member['id'], 'desc'=>$desc, 'content'=>$content, 'create_time'=>time()]);
        return $res ? $this->pass('反馈成功') : $this->miss('fail');
    }

    public function commentList($dy_id = '', $page = 1, $pagesize = 20)
    {
        $data = Db::name('dycomment')
                    ->alias('dc')
                    ->join('dymanic dy', 'dy.dy_id=dc.dy_id')
                    ->where(['dc.shenhe'=>1,'dy.userid'=>$this->member['id']])
                    ->field('dc.*,dy.title dy_title,dy.content as dy_content')
                    ->page($page)
                    ->limit($pagesize)
                    ->order('dc.comment_id desc')
                    ->select();
        $count = Db::name('dycomment')
                    ->alias('dc')
                    ->join('dymanic dy', 'dy.dy_id=dc.dy_id')
                    ->where(['dc.shenhe'=>1,'dy.userid'=>$this->member['id']])
                    ->cache(1800)
                    ->count();

        $users = Db::name('user')->where(['id'=>['in',array_column($data,'userid')]])->column('id,name,head_portrait,sex,age','id');
        foreach ($data as &$value) {
            $value['user'] = $users[$value['userid']] ?? false;
        }

        return $this->pass($data, 'data', ['paging' => ['page' => $page, 'pagesize' => $pagesize, 'count'=>$count]]);
    }

    public function update($dy_id = '', $title = '', $content = '', $cover = '')
    {
        $dy = Db::name('dymanic')->where(['dy_id'=>$dy_id, 'userid'=>$this->member['id']])->find();
        if (!$dy) return $this->miss('动态不存在');
        if ($dy['shenhe']==0) return $this->miss('动态审核中,不可修改');
        $update = [];
        if ($title) {
            $update['title'] = $title;
        }
        if ($content) {
            $update['content'] = $content;
        }
        if ($cover && $dy['cover']) {
            $update['cover'] = $cover;
        }
        if (sizeof($update)) {
            $checkDymanic = Db::name('config_system')->where(['title' => 'check_dymanic'])->value('content');
            $update['shenhe'] = $checkDymanic ? 0 : 1;
            $update['between'] = datetime();
        } else {
            return $this->miss('修改失败,请重试');
        }
        $res = Db::name('dymanic')->where(['dy_id'=>$dy_id])->update($update);
        return $res ? $this->pass('修改成功' . ($checkDymanic?',待审核':'')) : $this->miss('修改失败,请重试');
    }
}
